import time
import datetime
import uuid
import requests
import pymysql
from xml.etree import ElementTree
from functools import wraps
from app import app
from app.models import QTaskHistory
from exts import db


def get_db():
    db = pymysql.connect(host='127.0.0.1', port=3306, user="root", passwd="root", db="test", charset="utf8",
                         cursorclass=pymysql.cursors.DictCursor)
    db.set_charset('utf8')
    return db


def task_run_log(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        status = True
        start = time.time()
        try:
            res = func(*args, **kwargs)
            span_time = time.time() - start
        except Exception as e:
            status = False
            res = e
            span_time = 0
        with app.app_context() as f:
            task = QTaskHistory(
                id=uuid.uuid1().hex,
                task_id=kwargs.get('task_id'),
                task_name=kwargs.get('task_name'),
                func_name=func.__name__,
                time=int(start),
                user=kwargs.get('user'),
                status=status,
                log=str(res),
                span_time='{:.2f}'.format(span_time)
            )
            db.session.add(task)
            db.session.commit()
        return res

    return wrapper


def task_run_log_bak(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print('task_run_log_bak', datetime.datetime.now(), func.__name__, args, kwargs)
        _db = get_db()
        with _db.cursor() as cursor:
            task = dict(
                id=uuid.uuid1().hex,
                task_id=kwargs.get('task_id'),
                task_name=kwargs.get('task_name'),
                func_name=func.__name__,
                time=int(time.time()),
                user=kwargs.get('user')
            )
            _sql = 'insert into `qiao_task_history` (`id`,`task_id`,`task_name`,`func_name`,`time`,`user`)values ' \
                   '("{id}","{task_id}","{task_name}","{func_name}","{time}","{user}")'.format(**task)
            cursor.execute(_sql)
            # cursor.executemany(_sql)
            _db.commit()
        res = func(*args, **kwargs)
        return res

    return wrapper


@task_run_log
def get_xml_data(cabinet=[], **kwargs):
    db = get_db()
    try:
        with db.cursor() as cursor:
            _time = int(time.time())
            for val in cabinet:
                url = 'http://192.168.0.100/{}.xml?_={}'.format(val, _time)
                print(datetime.datetime.now(), url)
                text_str = requests.get(url)
                text_str.encoding = 'utf-8'
                node = ElementTree.XML(text_str.text)
                datas = {k[0]: k[1] for k in
                         [d.split(':') for d in node.find('CurRunData').text.strip().split('|') if d]}
                _sql = 'insert into `qiao_xml_data` (`c_id`,`xml_id`,`data`,`time`) values (%s,%s,%s,%s)'
                # cursor.execute(_sql)
                cursor.executemany(_sql, [(k, val, v, _time) for k, v in datas.items()])
                db.commit()
        return 'OK'
    except Exception as e:
        print('db error:', e)
        db.rollback()
        db.close()
        raise Exception(e)
    # finally:
    #     db.close()
    #     return 'OK'


@task_run_log
def test(c, **kwargs):
    print(c,kwargs)
    return
